import csv
import datetime
import os

import numpy as np
from matplotlib import colors

colors.CSS4_COLORS
import matplotlib.pyplot as plt

filexame = 'data1.txt'
# f = open(fileName)
# data = f.read()
# data1 = data.splitlines()
statrtime = datetime.datetime.now()
print(statrtime)
modenumber = 5
pulsewidth = 40
a0=20
space=1000
cursor_1_1 = 19135
cursor_1_2 = 24135
cursor_2_1 = 51380
cursor_2_2 = 56380
cursor_3_1 = 0
cursor_3_2 = 100000

#x10=0
x20=0
sweeps = 0
det1 = 0
det2 = 0
det3 = 0
count1 = 0
count2 = 0
count3 = 0
coin12 = 0
coin13 = 0
coin23 = 0
coin123 = 0
g12 = 0
g13 = 0
g23 = 0
alpha_1_23 = 0
g12_err = 0
g13_err = 0
g23_err = 0
alpha_1_23_err = 0
channeltime1 = np.zeros(shape=(100000, 2))
channeltime2 = np.zeros(shape=(100000, 2))
channeltime3 = np.zeros(shape=(100000, 2))
channeltime12 = np.zeros(shape=(100000, 2))
coins12 = np.zeros(shape=(modenumber, modenumber))
counts1 = np.zeros(shape=(modenumber, 1))
counts2 = np.zeros(shape=(modenumber, 1))
counts3 = np.zeros(shape=(modenumber, 1))
g2 = np.zeros(shape=(modenumber, modenumber))
time1 = np.zeros(shape=(modenumber, 1))
time2 = np.zeros(shape=(modenumber, 1))
time3 = np.zeros(shape=(modenumber, 1))

currentdir = os.getcwd()
filename = os.listdir(currentdir)
# for root, dirs, files in os.walk(currentdir, topdown=False):
#     for name in files:
#         if name.endswith('.txt'):
for name in filename:
    if name.endswith('.txt'):
        # x=os.path.abspath(name)#如果以图片jpg结尾则为真，同样对于png,bmp,txt也适用
        # x = os.path.join(root, name)
        print(name)
        with open(name) as datacal:
            for content in datacal:
                arr = content.split(',')
                arr = list(map(int, arr))
                arr[0] = arr[0] / 10
                if arr[1] == 4:
                    sweeps = sweeps + 1
                    if det1 == 1 and det2 == 1:
                        if cursor_2_1-a0 < x20< cursor_2_2-a0 or cursor_2_1-a0+space < x20< cursor_2_2-a0+space or
                            cursor_2_1 - a0 + 2*space < x20 < cursor_2_2 - a0 + 2*space+cursor_2_1-a0+3*space < x20< cursor_2_2-a0+3*space
                            +cursor_2_1-a0+space < x20< cursor_2_2-a0+space
                        channeltime12[x20][1] = channeltime12[x20][1] + 1
                        coin12 = coin12 + 1
                        coins12[0][x22] = coins12[0][x22] + 1  # 暂不考虑3通道多模存储
                        if det3 == 1:  # 暂不考虑3通道多模存储
                            coin13 = coin13 + 1
                            coin23 = coin23 + 1
                            coin123 = coin123 + 1
                        else:
                            pass
                    elif det1 == 1 and det3 == 1:
                        coin13 = coin13 + 1
                    elif det2 == 1 and det3 == 1:
                        coin23 = coin23 + 1
                    else:
                        pass
                    det1 = 0
                    det2 = 0
                    det3 = 0
                elif arr[1] == 1 and -1 < arr[0] < 100000:
                    x1 = int(arr[0])
                    channeltime1[x1][1] = channeltime1[x1][1] + 1
                    if cursor_1_1 < arr[0] < cursor_1_2:  # jiacursor
                        det1 = det1 + 1
                        count1 = count1 + 1
                        # print(arr[0])
                        x10 = int(arr[0])
                        x11 = int((arr[0] - cursor_1_1) / pulsewidth)  # 设置模式起始时间，模式编号

                        counts1[x11][0] = counts1[x11][0] + 1

                elif arr[1] == 2 and 0 < arr[0] < 100000:
                    x2 = int(arr[0])
                    channeltime2[x2][1] = channeltime2[x2][1] + 1
                    if cursor_2_1 < arr[0] < cursor_2_2:
                        det2 = det2 + 1
                        count2 = count2 + 1
                        x20 = int(arr[0])
                        x22 = int((arr[0] - cursor_2_1) / pulsewidth)  # 设置模式起始时间，模式编号
                        time2[x22][0] = time2[x22][0] + 1
                        counts2[x22][0] = counts2[x22][0] + 1

                else:
                    pass
np.savetxt('coin12.csv', coins12, delimiter=',')
np.savetxt('counts1.csv', counts1, delimiter=',')
np.savetxt('counts2.csv', counts2, delimiter=',')
np.savetxt('channeltime1.csv', channeltime1, delimiter=',')
np.savetxt('channeltime2.csv', channeltime2, delimiter=',')
np.savetxt('channeltim12.csv', channeltime12, delimiter=',')
for i in np.arange(0, modenumber, 1):
    for j in np.arange(0, modenumber, 1):
        if counts1[i] != 0 and counts2[j] != 0:
            g2[i][j] = sweeps * coins12[i][j] / (counts1[i] * counts2[j])
print(g2)
#print(sweeps)
print('sweeps:', sweeps)
print('count1:', count1)
print('count2:', count2)
print('count3:', count3)
print('coin12:', coin12)
print('coin13:', coin13)
print('coin23:', coin23)
print('coin123:', coin123)
np.savetxt('g2.csv', g2, delimiter=',')
'''
if count1 != 0 and count2 != 0:
    g12 = round(coin12 * sweeps / (count1 * count2), 5)
    g12_err = round(np.sqrt(
        (coin12 / (count1 ** 2 * count2)) ** 2 * count1 +
        (coin12 / (count2 ** 2 * count1)) ** 2 * count2 +
        (1 / (count1 * count2)) ** 2 * coin12) * sweeps, 5)
if count1 != 0 and count3 != 0:
    g13 = round(coin13 * sweeps / (count1 * count3), 5)
    g13_err = round(np.sqrt(
        (coin13 / (count1 ** 2 * count3)) ** 2 * count1 +
        (coin13 / (count3 ** 2 * count1)) ** 2 * count3 +
        (1 / (count1 * count3)) ** 2 * coin13) * sweeps, 5)
    # if result[2] != 0 and result[3] != 0:
    # self.g23 = round(result[6] * result[0] / (result[2] * result[3]), 3)
    g23 = round((coin12 + coin13) * sweeps / (
            (count2 + count3) * count1), 5)  # 23通道同共同计数，再和1通道关联
    g23_err = round(np.sqrt(
        ((coin12 + coin13) / (count1 ** 2 * (
                count2 + count3))) ** 2 * count1 +
        (coin12 / (
                (count2 + count3) ** 2 * count1)) ** 2 * (
                count2 + count3) +
        (1 / (count1 * (count2 + count3))) ** 2 * (
                coin12 + coin13)) * sweeps, 5)
if coin12 != 0 and coin13 != 0:
    # self.alpha_1_23 = round(result[7] * result[1] / (result[4] * result[5]), 3)
    alpha_1_23 = round(
        coin123 * count1 / (coin12 * coin13), 5)
    alpha_1_23_err = round(np.sqrt(
        (coin123 / (coin12 * coin13)) ** 2 * count1 +
        (count1 / (coin12 * coin13)) ** 2 * coin123
        + (count1 * coin123 / (
                coin12 ** 2 * coin13)) ** 2 * coin12 +
        (count1 * coin123 / (
                coin13 ** 2 * coin12)) ** 2 * coin13), 5)
with open('results.csv', 'w') as f_handle2:
    writer = csv.writer(f_handle2)
   # f_handle2.write(str(count1),str(count2), delimiter=',')
    writer.writerow([str(sweeps),str(count1),str(count2),str(count3),str(coin12),str(coin13),str(coin23),str(coin123),str(g12),str(g13),str(g23),str(alpha_1_23),
                     str(g12_err),str(g13_err),str(g23_err),str(alpha_1_23_err),str(datetime.datetime.now())])  # 写入标签
    f_handle2.close()
print('sweeps:', sweeps)
print('count1:', count1)
print('count2:', count2)
print('count3:', count3)
print('coin12:', coin12)
print('coin13:', coin13)
print('coin23:', coin23)
print('coin123:', coin123)
print('g12:', g12, '±', g12_err)
print('g13:', g13, '±', g13_err)
print('g1/23:', g23, '±', g23_err)
print('alpha:', alpha_1_23, '±', alpha_1_23_err)
'''

plt.figure(12)  # ,figsize=(6,9))

plt.subplot(311)
plt.plot(channeltime1)

plt.subplot(312)
plt.plot(channeltime2)

plt.subplot(313)
plt.plot(channeltime12)
plt.subplots_adjust(left=None, bottom=None, right=None, top=None,
                    wspace=None, hspace=0.474)

plt.show()

# plt.plot(channeltime1)
# plt.show()
# plt.plot(channeltime2)
# plt.show()
# print(channeltime1)
# cal(filexame)
# d=np.array(channeltime2)
# #d1=d[:,1]
# plt.hist(x = d, # 指定绘图数据
#        bins =1000,# 'auto', # 指定直方图中条块的个数
#        color = '#1E90FF', # 指定直方图的填充色
#        edgecolor = 'steelblue' # 指定直方图的边框色
#        )
#
# print(time*1000,'s')
# plt.show()
print(datetime.datetime.now())
